

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../plugins/layui/css/layui.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../layuiadmin/style/admin.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/style.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/metroStyle.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="../plugins/toastr/toastr.min.css?v=${.Config.basic.version}">
    <link rel="stylesheet" href="../plugins/font-awesome-4.7.0/css/font-awesome.min.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="//at.alicdn.com/t/font_2575369_9n08winu4t8.css?spm=a313x.7781069.1998910419.40&file=font_2575369_9n08winu4t8.css" media="all">
    <link rel="stylesheet" href="../css/ztree.css?v=${.Config.basic.version}" media="all">

    <style>

        .layui-form-item .layui-input-inline {
            float: left;
            width: 150px;
            margin-right: 10px;
        }
        .layui-form-item {
            margin-top: 5px;
            margin-bottom: 10px;
        }
        .layui-form-select dl {
            max-height: 150px;
        }
    </style>
    <style>
        /* .layui-table-view .layui-table td, .layui-table-view .layui-table th {
            padding: 5px 0;
            border-top: 1px solid #404453;
            border-left: 1px solid #404453;
            border-bottom: 1px solid #404453;
            border-right: 1px solid #404453;
        } */
        xm-select {
            background-color: #19295a !important;
            border: 0px solid #E6E6E6 !important;
        }
    </style>
</head>
<body>

<div class="">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">用户角色</label>
                        <div class="layui-input-inline">
                            <select name="select_role" lay-verify="" lay-search="">
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">关键字</label>
                        <div class="layui-input-inline">
                            <input type="text" name="txt_key" lay-verify="" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="submit" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="" lay-filter="btn_search"><i class="layui-icon layui-icon-search"></i>查询</button>
                    </div>

                    <div class="layui-inline fr">
                        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal  action-edit layui-hide" lay-event="add" onclick="onAdd();"><i class="layui-icon layui-icon-add-circle"></i> 增加用户</button>
                    </div>

                </div>
            </form>

            <table class="layui-hide" id="user_table" lay-filter="user_table"></table>


            <script type="text/html" id="user_table_action_bar">
                
            </script>
        </div>
    </div>
</div>

<script src="../plugins/layui/layui.js"></script>
<script src="../plugins/layui/xm-select-v1.2.4.js?v=${.Config.basic.version}"></script>
<script src="../plugins/jquery/jquery-3.6.0.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.core.min.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.excheck.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.exedit.js?v=${.Config.basic.version}"></script>
<script src="../plugins/jquery.slimscroll.min.js"></script>
<script src="../plugins/toastr/toastr.min.js"></script>
<script src="../plugins/moment.min.js"></script>
<script src="../js/utils.js"></script>
<script src="../js/verify.js"></script>
<script src="../js/func.js?v=${.Config.basic.version}"></script>
<script>
    var table=null;
    var form=null;
    var userTable=null;
    var sys_roles=null;
    var token = window.localStorage.getItem("token");
    var user_info=JSON.parse(window.localStorage.getItem("user_info"));
    var func_url="${.func_url}";
    var actions=[];
    token = 'Bearer ' + token;

    var SYS_POSITION_TYPE=[];

    var roles = [];
    var farms=[];
    var gourps=[];
    var areas=[];

    var xselect_area=null;
    var xselect_farm=null;

    var tree_setting = {
        view: {
            dblClickExpand: false,
            fontCss: getFont,
            nameIsHTML: true,
            //addDiyDom:addDiyDom
        },
        
        callback: {
            onClick: treeOnClick,
            //onRightClick: OnRightClick,
            onCheck: zTreeOnCheck
        },
        check: {
            enable: true,
            chkboxType : { "Y" : "ps", "N" : "ps" }
        },
    };
    function addDiyDom(treeId, treeNode){
        selectedTreeNode = treeNode;
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
        var addStr = "<span class='layui-text-white select' nodeid='"+treeNode.tId+"' id='selectBtn_" + treeNode.tId
            + "' title='全选'' onfocus='this.blur();'>全选/</span>";

        var removeStr = "<span class='layui-text-white unselect' nodeid='"+treeNode.tId+"' id='unselectBtn_" + treeNode.tId
            + "' title='全不选' onfocus='this.blur();'>全不选</span>";

        sObj.after(addStr);
        sObj.after(removeStr);
        var btn = $("#unselectBtn_"+treeNode.tId);
        if (btn) btn.bind("click", function(event){
            var tid = $(this).attr("nodeid");
            var node = zTree.getNodeByTId(tid);
            onUnSelectAll(node);
        });

        btn = $("#selectBtn_" + treeNode.tId);
        if (btn) btn.bind("click", function (event) {
            var tid = $(this).attr("nodeid");
            var node = zTree.getNodeByTId(tid);
            onSelectAll(node);
            return false;
        });
    }
    function getFont(treeId, node) {
        return node.font ? node.font : {};
    }
    function treeOnClick(event, treeId, treeNode) {
    }
    function treeOnExpand(event, treeId, treeNode) {
    }
    function zTreeOnCheck(event, treeId, treeNode) {
    }
    function OnRightClick(event, treeId, treeNode) {
    }

    function treeOnCollapse(event, treeId, treeNode) {
        console.info(treeNode);
    }

    function onSelectAll(treeNode){
        console.info("onSelectAll",treeNode);
    }

    function onUnSelectAll(treeNode){
        console.info("onUnSelectAll",treeNode);
    }

    layui.config({
        base: '../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table','form'], function(){
        $ = layui.$;
        form = layui.form;
        table = layui.table;
        toastr.options = {
            "closeButton": false, //是否显示关闭按钮
            "debug": false, //是否使用debug模式
            "positionClass": "toast-top-center",//弹出窗的位置
            "showDuration": "300",//显示的动画时间
            "hideDuration": "1000",//消失的动画时间
            "timeOut": "2000", //展现时间
            "extendedTimeOut": "1000",//加长展示时间
            "showEasing": "swing",//显示时的动画缓冲方式
            "hideEasing": "linear",//消失时的动画缓冲方式
            "showMethod": "fadeIn",//显示时的动画方式
            "hideMethod": "fadeOut" //消失时的动画方式
        };

        $.ajax({
            type: 'GET',
            url: '../Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                toastr.warning('加载操作信息失败');
            }
        });
        

        $.ajax({
            type: 'GET',
            url:"/Api/Dictionary",
            data: {code:"SYS_POSITION_TYPE"},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            success: function(data){
                if(data){
                    var list=data.data;
                    console.info(list);
                    SYS_POSITION_TYPE=list;
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                //layer.closeAll('loading');
            },
            dataType: "json"
        });

        loadRoleList().then(function(res) {
            if(res.code>=0){
                roles = res.data;
                if(roles.length>0){
                    renderRoleSelect();
                }
            }
        });
        



        //监听提交
        form.on('submit(btn_search)', function(data){
            search({role:data.field.select_role,key:data.field.txt_key});
            return false;
        });
        form.on('submit(btn_ok)', function(data){
            var obj = data.field; //获取提交的字段
            var type="";
            if(obj.id.length==0){
                type="POST";
            }else{
                type="PUT"
            }

            var area_id_arr=[];
			var items=xselect_area.getValue();
			for(var i=0;i<items.length;i++){
				area_id_arr.push(items[i].id);
			}
			obj.area_ids=area_id_arr.join(",");

            var farm_id_arr=[];
			var items=xselect_farm.getValue();
			for(var i=0;i<items.length;i++){
				farm_id_arr.push(items[i].id);
			}
			obj.farmid_ids=farm_id_arr.join(",");

            console.info(obj);
            if(obj.position_type=="group"){
                obj.area_ids = "";
                obj.farmid_ids = "";
            }
            else if(obj.position_type == "area"){
                if(obj.area_ids==""){
                    toastr.warning("未设置所属的组团/区域,请设置后重试!");
                    return false;
                }
                obj.farmid_ids = "";
            }
            else if(obj.position_type == "farm"){
                if(obj.area_ids==""){
                    toastr.warning("未设置所属的组团/区域,请设置后重试!");
                    return false;
                }
                if(obj.farmid_ids==""){
                    toastr.warning("未设置所属的场区,请设置后重试!");
                    return false;
                }
            }
            else{
                if(obj.area_ids==""){
                    toastr.warning("未设置所属的组团/区域,请设置后重试!");
                    return false;
                }
                if(obj.farmid_ids==""){
                    toastr.warning("未设置所属的场区,请设置后重试!");
                    return false;
                }
            }

            //return false
            $.ajax({
                type: type,
                url: '../Api/User',
                data: obj,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code>=0){
                        toastr.success('保存成功');
                        layui.table.reload('user_table'); //重载表格
                        layer.close(lay_index); //再执行关闭
                    }else{
                        layer.alert('保存失败:'+data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('保存失败');
                }
            });
        });
        form.on('submit(btn_allocate)', function(data){
            var field = data.field;
            var nodes = zTree.getCheckedNodes(true);
            console.info(field,nodes);
            var farmidArray=[];
            var houseidArray=[];
            for(var i=0;i<nodes.length;i++){
                if(nodes[i].type=="farm"){
                    farmidArray.push(nodes[i].id);
                    
                }else if(nodes[i].type=="house"){
                    houseidArray.push(nodes[i].id);
                }
            }
            var farmids = farmidArray.join(",");
            var houseids = houseidArray.join(",");
            console.info("farmids",farmids);
            console.info("houseids",houseids);
            var obj={
                userid:field.userid,
                farmids:farmids,
                houseids:houseids
            };

            layer.load(1);
            $.ajax({
                type: "PUT",
                url: '../Api/User/Org',
                data: obj,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code>=0){
                        toastr.success('保存成功');
                        layui.table.reload('user_table'); //重载表格
                        layer.close(lay_index); //再执行关闭
                    }else{
                        layer.alert('保存失败:'+data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('保存失败');
                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },
            });
        });

        loadTable();
    });

    function loadTable(){
        console.info(user_info);
        var cols=[];
        if(user_info.is_admin){
            cols = [[
                //{type: 'checkbox', fixed: 'left'}
                {field:'userid', title:'账号', unresize: false, sort: true,templet: function(d){
                    var html = '';
                    if(d.userid == user_info.userid){
                        //当前
                        html += (d.userid+"<button style='margin-left:10px;' class=\"layui-btn layui-btn-green layui-btn-xs\">我</button>");
                    }else{
                        html = d.userid;
                    }
                    return html;
                }}
                ,{field:'name', title:'用户名'}

                ,{field:'role_names', title:'角色',templet: function(d){
                        var html='';
                        if(d.role_names) {
                            var names = d.role_names.split(',');
                            for (var i = 0; i < names.length; i++) {
                                html += "<button class=\"layui-btn layui-btn-primary layui-btn-xs\">" + names[i] + "</button>";
                            }
                        }
                        return html;
                    }}
                ,{field:'group_name', title:'集团', width:120, sort: false}
                ,{field:'area_names', title:'区域/组团', width:150, sort: false}
                ,{field:'farmnames', title:'养殖场', width:150, sort: false}
                ,{field:'status', title:'状态', width:80,align:'center',hide:true,templet: function(d){
                        return '<em>'+ (d.status==0?'无效':'有效') +'</em>'
                    }}
                ,{field:'', title:'状态', width:80,align:'center',templet: function(d){
                        var checked = d.status==1 ?"checked":"";
                        return '<input type="checkbox" userid="'+d.userid+'" name="'+d.name+'" lay-skin="switch" lay-filter="check_status" lay-text="有效|失效"  '+checked+'>';
                    }}
                ,{field:'is_admin', title:'管理员', width:80,align:'center',templet: function(d){
                        var checked = d.is_admin ?"checked":"";
                        return '<input type="checkbox" userid="'+d.userid+'" name="'+d.name+'" lay-skin="primary" lay-filter="check_admin"  title="' + d.is_admin + '"  ' + checked + ' >';
                    }}
                // ,{field:'email', title:'邮箱', width:180,  templet: function(d){
                //         return '<em>'+ (d.email?d.email:'') +'</em>'
                //     }}
                // ,{field:'phone', title:'手机', width:150, sort: true}
                ,{field:'create_by', title:'创建人', width:120}
                ,{field:'create_time', title:'创建时间', width:170}
                ,{fixed: 'right', title:'操作', width:200, templet:function(d){
                    var html = "";
                    html +='<a class="text-underline layui-hide action-edit " lay-event="edit">编辑</a><span class="shortGreyLine layui-hide action-edit "></span>';
                    html +='<a class="text-underline layui-hide action-delete" lay-event="del">删除</a><span class="shortGreyLine layui-hide action-delete "></span>';
                    // html +='<a class="text-underline layui-hide action-allocate" lay-event="org">组织权限</a><span class="shortGreyLine layui-hide action-delete "></span>';
                    html +='<a class="text-underline layui-hide action-reset" lay-event="reset_pwd">重置密码</a>';
                    return html;
                }}
            ]];
        }else{
            if(user_info.position_type=="group" || user_info.position_type=="area" || user_info.position_type=="farm"){

                cols = [[
                    //{type: 'checkbox', fixed: 'left'}
                    {field:'userid', title:'账号', unresize: false, sort: true,templet: function(d){
                        var html = '';
                        if(d.userid == user_info.userid){
                            //当前
                            html += (d.userid+"<button style='margin-left:10px;' class=\"layui-btn layui-btn-green layui-btn-xs\">我</button>");
                        }else{
                            html = d.userid;
                        }
                        return html;
                    }}
                    ,{field:'name', title:'用户名'}

                    ,{field:'role_names', title:'角色',templet: function(d){
                            var html='';
                            if(d.role_names) {
                                var names = d.role_names.split(',');
                                for (var i = 0; i < names.length; i++) {
                                    html += "<button class=\"layui-btn layui-btn-primary layui-btn-xs\">" + names[i] + "</button>";
                                }
                            }
                            return html;
                        }}
                    ,{field:'group_name', title:'集团', width:120, sort: false}
                    ,{field:'area_names', title:'区域/组团', width:150, sort: false}
                    ,{field:'farmnames', title:'养殖场', width:150, sort: false}
                    ,{field:'status', title:'状态', width:80,align:'center',hide:true,templet: function(d){
                        return '<em>'+ (d.status==0?'无效':'有效') +'</em>'
                    }}
                    ,{field:'', title:'状态', width:80,align:'center',templet: function(d){
                        var checked = d.status==1 ?"checked":"";
                        return '<input type="checkbox" userid="'+d.userid+'" name="'+d.name+'" lay-skin="switch" lay-filter="check_status" lay-text="有效|失效"  '+checked+'>';
                    }}
                    ,{field:'create_by', title:'创建人', width:120}
                    ,{field:'create_time', title:'创建时间', width:170}
                    ,{fixed: 'right', title:'操作', width:200, templet:function(d){
                        var html = "";
                        html +='<a class="text-underline layui-hide action-edit " lay-event="edit">编辑</a><span class="shortGreyLine layui-hide action-edit "></span>';
                        html +='<a class="text-underline layui-hide action-delete" lay-event="del">删除</a><span class="shortGreyLine layui-hide action-delete "></span>';
                        // html +='<a class="text-underline layui-hide action-allocate" lay-event="org">组织权限</a><span class="shortGreyLine layui-hide action-delete "></span>';
                        html +='<a class="text-underline layui-hide action-reset" lay-event="reset_pwd">重置密码</a>';
                        return html;
                    }}
                ]];
            }
            else{
                cols = [[
                    //{type: 'checkbox', fixed: 'left'}
                    {field:'userid', title:'账号', unresize: false, sort: true,templet: function(d){
                        var html = '';
                        if(d.userid == user_info.userid){
                            //当前
                            html += (d.userid+"<button style='margin-left:10px;' class=\"layui-btn layui-btn-green layui-btn-xs\">我</button>");
                        }else{
                            html = d.userid;
                        }
                        return html;
                    }}
                    ,{field:'name', title:'用户名'}

                    ,{field:'role_names', title:'角色',templet: function(d){
                            var html='';
                            if(d.role_names) {
                                var names = d.role_names.split(',');
                                for (var i = 0; i < names.length; i++) {
                                    html += "<button class=\"layui-btn layui-btn-primary layui-btn-xs\">" + names[i] + "</button>";
                                }
                            }
                            return html;
                        }}
                    ,{field:'group_name', title:'集团', width:120, sort: false}
                    ,{field:'area_names', title:'区域/组团', width:150, sort: false}
                    ,{field:'farmnames', title:'养殖场', width:150, sort: false}
                    ,{field:'status', title:'状态', width:80,align:'center',hide:true,templet: function(d){
                        return '<em>'+ (d.status==0?'无效':'有效') +'</em>'
                    }}
                    ,{field:'create_by', title:'创建人', width:120}
                    ,{field:'create_time', title:'创建时间', width:170}
                    ,{fixed: 'right', title:'操作', width:120, templet:function(d){
                        var html = "";
                        html +='<a class="text-underline" layui-hide action-reset lay-event="reset_pwd">重置密码</a>';
                        return html;
                    }}
                ]];
            }
        }
        userTable = table.render({
            elem: '#user_table'
            //,data:data
            ,url:'../Api/User/List'
            ,height: 'full-90'
            ,method:'GET'
            ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
            ,where: {}
            ,page: false
            //,limit:30
            //,toolbar: '#user_table_toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['']
            ,title: '用户数据表'
            ,even:false
            ,size: 'sm' //小尺寸的表格
            //,skin: 'nob' //无框风格
            ,cols: cols
            ,done: function(res, curr, count){
                var index=-1;
                //分类显示中文名称
                $("[data-field='status']").children().each(function () {
                    index++;
                    if ($(this).text() == '无效'){
                        $('tr').eq(index).css("background-color","#aaa");
                    }
                });

                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            }
        });

        //头工具栏事件
        table.on('toolbar(user_table)', function(obj){
            switch(obj.event){
                case 'addUser':
                    onAdd();
                    break;

            };
        });

        //监听行工具事件
        table.on('tool(user_table)', function(obj){
            var data = obj.data;
            console.log(data)
            if(obj.event === 'del'){
                onDelete(data);
            }
            else if(obj.event === 'reset_pwd'){
                onResetPwd(data)
            }
            else if(obj.event === 'edit'){
                onEdit(data);
            }else if(obj.event === 'org'){
                onAllocateOrg(data);
            }
        });

        //监听行checkbox事件
        form.on('checkbox(check_admin)', function(obj){
            onSetAdmin(obj);
        });
        form.on('switch(check_status)', function(obj){
            onSetStatus(obj);
        });
    
    }

    //加载校色
    function loadRoleList(){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: '../Api/Role/List',
                data: {},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }
    
    //加载集团
    function loadGroupList(){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: '../Api/Group',
                data: {},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //加载组团
    function loadAreaList(){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: '../Api/Area',
                data: {},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    //加载养殖场
    function loadFarmList(){
        var promise = new Promise(function(resolve, reject) {
            $.ajax({
                type: 'GET',
                url: '../Api/Farm/List',
                data: {},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function (data) {

                    if (data && data.code>=0) {
                        resolve(data);
                    }else{
                        resolve(data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    reject(err);
                },
                complete: function(XMLHttpRequest, textStatus) {

                },
                dataType: "json"
            });
        });
        return promise;
    }

    function renderRoleSelect(){

        var html="";
        for(var i=0;i<roles.length;i++){
            html+="<input type=\"checkbox\" name=\"role["+roles[i].id+"]\" title=\""+roles[i].name+"\" >";
        }
        $("#check_roles").html(html);
        form.render('checkbox');

        var html="<option value=\"\">全部</option>";
        for(var i=0;i<roles.length;i++) {
            html += "<option value=\"" + roles[i].id + "\">" + roles[i].name + "</option>";
        }
        $("select[name='select_role']").html(html);

        html="<option value=\"\">请选择</option>";
        for(var i=0;i<roles.length;i++) {
            html += "<option value=\"" + roles[i].id + "\">" + roles[i].name + "</option>";
        }

        $("select[name='role_id']").html(html);
        form.render('select');

        
        form.on('select(role_id)', function(data){
            console.info(data.value);
            bindRoleChange(data.value);
        });
    }

    //改变角色联动
    function bindRoleChange(role_id){
        var position_type = '';
        $("#position_type").val("");
        for(var i=0;i<roles.length;i++){
            if(role_id == roles[i].id){
                position_type = roles[i].position_type;
                $("#position_type").val(position_type);
                $("#position_type_name").val(getPositionName(position_type));
                break;
            }
        }

        if(position_type=="group"||position_type=="service"){
            $(".div-area").addClass("layui-hide");
            $(".div-farm").addClass("layui-hide");
        }
        else if(position_type=="area"){
            $(".div-area").removeClass("layui-hide");
            $(".div-farm").addClass("layui-hide");
        }
        else if(position_type=="farm"){
            $(".div-area").removeClass("layui-hide");
            $(".div-farm").removeClass("layui-hide");
        }
        else if(position_type=="self"){
            $(".div-area").removeClass("layui-hide");
            $(".div-farm").removeClass("layui-hide");
        }
        else if(position_type=="engineer"){
            $(".div-area").removeClass("layui-hide");
            $(".div-farm").removeClass("layui-hide");
        }
    }

    
    function renderGroupSelect(){
        //栏舍下拉
        var html="<option selected value=''></option>";
        for(var i=0;i<gourps.length;i++){
            if(i==0){
                var selected="  ";
            }
            
            html+="<option "+selected+" value=\""+gourps[i].group_code+"\">"+gourps[i].group_name+"</option>";
        }

        $("select[name='group_code']").html(html);

        form.render('select');

        form.on('select(group_code)', function(data){
            console.info(data.value);
            bindGourpChange(data.value);
        });
    }

    //改变集团联动
    function bindGourpChange(group_code){
        var matchs = [];
        for(var i=0;i<areas.length;i++){
            if(areas[i].group_code == group_code){
                matchs.push(areas[i]);
            }
        }
        renderAreaSelect(matchs);
    }

    function renderAreaSelect(data){
        console.info("renderAreaSelect",data);
        xselect_area = xmSelect.render({
            el: '#xselect_area', 
            tips: '选择',
            filterable: true,
            direction: 'auto',
            theme: {
                color: '#0081ff'
            },
            prop: {
                name: 'name',
                value: 'id',
            },
            data: data,
            on: function(data){
                //arr:  当前多选已选中的数据
                var arr = data.arr;
                //change, 此次选择变化的数据,数组
                var change = data.change;
                //isAdd, 此次操作是新增还是删除
                var isAdd = data.isAdd;
                
                //alert('已有: '+arr.length+' 变化: '+change.length+', 状态: ' + isAdd)
                console.info("on renderAreaSelect:",arr);

                var id_arr = [];
                for(var i=0;i<arr.length;i++){
                    id_arr.push(arr[i].id);
                }
                var area_ids = id_arr.join(",");
                bindAreaChange(area_ids);

            },
        });
    }

    function bindAreaChange(area_ids){
        var arr = area_ids.split(",");
        var list = [];
        for(var i=0;i<arr.length;i++){
            for(var x = 0;x<farms.length;x++){
                if(arr[i] == farms[x].area_id){
                    list.push(farms[x]);
                }
            }
        }
        renderFarmSelect(list);
    }

    function renderFarmSelect(data){
        //栏舍下拉
        /*var html="<option selected value=''></option>";
        for(var i=0;i<farms.length;i++){
            var selectd="";
            html+="<option "+selectd+" value=\""+farms[i].id+"\">"+farms[i].farmname+"</option>";
        }

        $("select[name='default_farm']").html(html);

        form.render('select');*/

        xselect_farm = xmSelect.render({
            el: '#xselect_farm', 
            tips: '选择',
            filterable: true,
            direction: 'auto',
            theme: {
                color: '#0081ff'
            },
            prop: {
                name: 'farmname',
                value: 'id',
            },
            data: data
        });
    }

    

    function onAdd() {
        

        $("#form")[0].reset();
        layui.form.render();
        layer.open({
            //area: 'auto',
            area:['450px','80%'],
            type: 1,
            shade: 0.3,
            shadeClose:true,
            offset: '50px',
            title: '新增', //不显示标题
            content: $('#form'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定', '取消']
            ,yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_ok");
                submit.click();
            }
        });


        Promise.all([loadGroupList(), loadAreaList(), loadFarmList()]).then(values => {
            console.log('3个请求都完成:', values);
            if(values[0].code>=0){
                gourps = values[0].data;
                if(gourps.length>0){
                    renderGroupSelect();
                }
            }
            if(values[1].code>=0){
                areas = values[1].data;
                if(areas.length>0){
                    renderAreaSelect(areas);
                }
            }
            if(values[2].code>=0){
                farms = values[2].data;
                if(farms.length>0){
                    renderFarmSelect(farms);
                }
            }
            
        }).catch(reason => {
            console.error('有请求被拒绝:', reason);
        });
    }

    function onEdit(item) {
        layer.open({
            //area: 'auto',
            area:['450px','80%'],
            type: 1,
            shade: 0.3,
            shadeClose:true,
            offset: '50px',
            title: '修改', //不显示标题
            content: $('#form'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定', '取消']
            ,yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_ok");
                submit.click();
            }
        });

        


        Promise.all([loadGroupList(), loadAreaList(), loadFarmList()]).then(values => {
            console.log('3个请求都完成:', values);
            if(values[0].code>=0){
                gourps = values[0].data;
                if(gourps.length>0){
                    renderGroupSelect();
                }
            }
            if(values[1].code>=0){
                areas = values[1].data;
                if(areas.length>0){
                    renderAreaSelect(areas);
                }
            }
            if(values[2].code>=0){
                farms = values[2].data;
                if(farms.length>0){
                    renderFarmSelect(farms);
                }
            }


            layer.load(1);
            $.ajax({
                type: 'GET',
                url:"../Api/User/List",
                data: {id:item.id},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                success: function(res){
                    if(res){
                        var obj=res.data[0];
                        /*var obj={}
                        if(item.role_ids){
                            var roles=item.role_ids.split(',');
                            for(var i=0;i<roles.length;i++){
                                var name="role["+roles[i]+"]";
                                obj[name]=true;
                            }
                        }*/

                        if(obj.role_ids){
                            var role_ids=obj.role_ids.split(',');
                            if(role_ids.length>0){
                                obj["role_id"] = role_ids[0];
                            }
                        }
                        
                        obj["id"]=item.id;
                        obj["userid"]=item.userid;
                        obj["name"]=item.name;
                        obj["email"]=item.email;
                        obj["phone"]=item.phone;
                        form.val("form", obj);

                        

                        if(obj.role_id){
                            bindRoleChange(obj.role_id);
                        }
                        if(obj.group_code){
                            bindGourpChange(obj.group_code);
                        }
                        if(obj.area_ids){
                            bindAreaChange(obj.area_ids);
                        }
                        
                        

                        if(obj.area_ids){
                            xselect_area.append(obj.area_ids.split(","));
                        }
                        if(obj.farmid_ids){
                            xselect_farm.append(obj.farmid_ids.split(","));
                        }
                    }

                },
                complete: function(XMLHttpRequest, textStatus) {
                    layer.closeAll('loading');
                },
                dataType: "json"
            });
            
        }).catch(reason => {
            console.error('有请求被拒绝:', reason);
        });
    }

    function onDelete(item) {
        layer.confirm('确认删除'+item.name+"?", function(index){
            //obj.del();
            layer.close(index);
            $.ajax({
                type: 'DELETE',
                url: '../Api/User',
                data: item,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code==0){
                        //toastr.success('成功');
                        layui.table.reload('user_table'); //重载表格
                        layer.close(index); //再执行关闭
                    }else{
                        layer.alert('失败:'+data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('失败');
                }
            });
        });
    }

    function onResetPwd(item) {
        layer.confirm('确认重置'+item.name+"的密码?", function(index){
            //obj.del();
            layer.close(index);
            $.ajax({
                type: 'PUT',
                url: '../Api/User/ResetPwd',
                data: item,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code>=0){
                        toastr.success('处理成功');
                        layui.table.reload('user_table'); //重载表格
                        layer.close(index); //再执行关闭
                    }else{
                        layer.alert('失败:'+data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('失败');
                }
            });
        });
    }

    function onSetAdmin(obj) {
        var userid=$(obj.elem).attr('userid');
        var name=$(obj.elem).attr('name');
        var target_value=obj.elem.checked;

        if(user_info.is_admin==1){
            var title=target_value?"设置为管理员":"取消管理员";
            layer.confirm('确认要将'+name+title+"?", function(index){
                $.ajax({
                    type: 'PUT',
                    url: '../Api/User/SetAdmin',
                    data: {userid:userid,is_admin:target_value?1:0},
                    beforeSend: function(request) {
                        request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                    },
                    dataType: "json",
                    success: function (data) {
                        //console.info(data)
                        if(data.code>=0){
                            //toastr.success('成功');
                            layui.table.reload('user_table'); //重载表格
                            layer.close(index); //再执行关闭
                        }else{
                            layer.alert('失败:'+data.msg);
                            if(target_value){
                                $(obj.elem).prop("checked", false);
                            }else{
                                $(obj.elem).prop("checked", true);
                            }
                            form.render('checkbox');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.alert('失败');
                    }
                });
            },function (index) {
                //toastr.success('cancel');
                if(target_value){
                    $(obj.elem).prop("checked", false);
                }else{
                    $(obj.elem).prop("checked", true);
                }
                form.render('checkbox');
            });
        }else{
            toastr.warning("没有权限");
            if(target_value){
                $(obj.elem).prop("checked", false);
            }else{
                $(obj.elem).prop("checked", true);
            }
            form.render('checkbox');
        }
    }

    function onSetStatus(obj) {
        var userid=$(obj.elem).attr('userid');
        var name=$(obj.elem).attr('name');
        var target_value=obj.elem.checked;

        var title=target_value?"设置为有效":"设置为无效";
        var url=(target_value?"../Api/User/Enable":"../Api/User/Disable");
        layer.confirm('确认要将'+name+title+"?", function(index){
            $.ajax({
                type: 'PUT',
                url: url,
                data: {userid:userid},
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code>=0){
                        //layer.msg('成功');
                        layui.table.reload('user_table'); //重载表格
                        layer.close(index); //再执行关闭
                    }else{
                        layer.alert('失败:'+data.msg);
                        if(target_value){
                            $(obj.elem).prop("checked", false);
                        }else{
                            $(obj.elem).prop("checked", true);
                        }
                        form.render('checkbox');
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('失败');
                }
            });
        },function (index) {
            //layer.msg('cancel');
            if(target_value){
                $(obj.elem).prop("checked", false);
            }else{
                $(obj.elem).prop("checked", true);
            }
            form.render('checkbox');
        });
    }

    function onAllocateOrg(item){
        console.info(item);
        layer.open({
            //area: 'auto',
            area:['50%','70%'],
            type: 1,
            shade: 0.3,
            shadeClose:true,
            offset: '5%',
            title: '分配组织权限', //不显示标题
            content: $('#form_allocate'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定', '取消']
            ,yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_allocate");
                submit.click();
            }
        });

        form.val("form_allocate",{userid:item.userid});
        loadTree(item);
    }
    
    
    function loadTree(item) {
        layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/Topo',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                //var data=data.data;
                var nodes=setDataIcon(data.data);
                console.info(nodes);
                zTree = $.fn.zTree.init($("#treeDemo"), tree_setting, nodes);
                //zTree.expandAll(true);
                loadUserFarms(item.userid);
                loadUserHouses(item.userid);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                toastr.warning('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                //layer.closeAll('loading');
            },
        });
    }

    function loadUserFarms(userid) {
        layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/Farm/List/ByUser',
            data: {userid:userid},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res)
                if(res.code>=0){
                    var list = res.data;
                    if(list.length>0){
                        for(var i=0;i<list.length;i++){
                            var farmid = list[i].id;
                            var nodes = zTree.getNodesByParam("farmid", farmid, null);
                            if(nodes.length>0){
                                const node = nodes[0];
                                zTree.checkNode(node, true, false, null);
                            }
                        }
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                toastr.warning('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                //layer.closeAll('loading');
            },
        });
    }

    function loadUserHouses(userid) {
        layer.load(1);
        $.ajax({
            type: 'GET',
            url: '../Api/House/List/ByUser',
            data: {userid:userid},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (res) {
                console.info(res)
                if(res.code>=0){
                    var list = res.data;
                    if(list.length>0){
                        for(var i=0;i<list.length;i++){
                            var houseid = list[i].id;
                            var nodes = zTree.getNodesByParam("houseid", houseid, null);
                            if(nodes.length>0){
                                const node = nodes[0];
                                zTree.checkNode(node, true, false, null);
                            }
                        }
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                toastr.warning('加载信息失败');
            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
        });
    }

    //设置图标
    function setDataIcon(data){

        for(let i=0; i<data.length; i++){
            var node=data[i];

            node['font']={'color':'#333'};
            if(node.type=='group'){
                //node.name = "";
                node["icon"]="../plugins/zTree/css/metroStyle/img/net.png";
                //node.isParent=true;
                node.open = true;
            }
            else if(node.type=='area'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/area.png";
                //node.isParent=true;
                node.open = true;
            }
            else if(node.type=='farm'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/location.png";
                //node.isParent=true;
                node.open = false;
            }else if(node.type=='house'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/house.png";
                //node.isParent=false;
            }else if(node.type=='unit'){
                node["icon"]="../plugins/zTree/css/metroStyle/img/unit.png";
                //node.isParent=false;
            }
            if(node['children']){
                var data1=node.children;
                setDataIcon(data1);
            }
        }
        return data;
    }
    function search(params) {
        userTable.reload({
            where: params
            // ,page: {
            //     curr: 1 //重新从第 1 页开始
            // }
        });
    }

    function getPositionName(position_type){
        for(var i=0;i<SYS_POSITION_TYPE.length;i++){
            if(SYS_POSITION_TYPE[i].data_value == position_type){
                return SYS_POSITION_TYPE[i].data_text;
            }
        }
        return '';
    }

</script>
<script src="../js/check_screen.js?v=${.Config.basic.version}"></script>

</body>


<form class="layui-form " lay-filter="form" id="form" style="padding: 20px 30px 0 0;display:none;">
    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">id</label>
        <div class="layui-input-block">
            <input type="text" name="id" lay-verify="" placeholder="" autocomplete="off" class="layui-input" disabled>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 手机号</label>
        <div class="layui-input-block">
            <input type="text" name="userid" lay-verify="phone" lay-verType="tips" placeholder="手机号(用于系统登录)" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 姓名</label>
        <div class="layui-input-block">
            <input type="text" name="name" lay-verify="required" lay-verType="tips" placeholder="请输入昵称" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 角色 </label>
        <div class="layui-input-block">
            <select  name="role_id" lay-filter="role_id" lay-verify="" lay-verType="tips" lay-search="" style="width: 100%;" >
                <option value=""></option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 职务级别 </label>
        <div class="layui-input-block">
            <input type="text" id="position_type_name" name="position_type_name" readonly lay-verify="" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 职务级别 </label>
        <div class="layui-input-block">
            <input type="text" id="position_type" name="position_type" readonly lay-verify="" lay-verType="tips" placeholder="" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label"><span class="layui-text-red">*</span> 所属集团 </label>
        <div class="layui-input-block">
            <select  name="group_code" lay-filter="group_code" lay-verify="required" lay-verType="tips" lay-search="" style="width: 100%;" >
                <option value=""></option>
            </select>
        </div>
    </div>

    <div class="layui-form-item div-area layui-hide">
        <label class="layui-form-label"><span class="layui-text-red">*</span>所属组团</label>
        <div class="layui-input-block">
            <div id="xselect_area" name="xselect_area" class="xm-select-demo"></div>
        </div>
    </div>

    <div class="layui-form-item div-farm layui-hide">
        <label class="layui-form-label"><span class="layui-text-red">*</span>所属场区</label>
        <div class="layui-input-block">
            <!-- <select  name="default_farm" lay-filter="default_farm" lay-verify="" lay-search="" style="width: 100%;" >
                <option value=""></option>
            </select> -->

            <div id="xselect_farm" name="xselect_farm" class="xm-select-demo"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-block">
            <input type="text" name="email" lay-verify="" lay-verType="tips" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
        </div>
    </div>
    <!-- <div class="layui-form-item">
        <label class="layui-form-label">手机号码</label>
        <div class="layui-input-block">
            <input type="text" name="phone" lay-verify="" placeholder="请输入手机号码" autocomplete="off" class="layui-input">
        </div>
    </div> -->

    
    
    <!-- <div class="layui-form-item">
        <label class="layui-form-label">角色</label>
        <div class="layui-input-block" id="check_roles">
        </div>
    </div> -->
    <!--<div class="layui-form-item">
        <label class="layui-form-label">管理员</label>
        <div class="layui-input-block">
            <input type="checkbox"  name="admin" lay-skin="switch" lay-filter="switchAdmin" lay-text="是|否">
        </div>
    </div>-->
    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_ok" id="btn_ok" value="确认添加">
        <input type="button" lay-submit lay-filter="btn_cancel" id="btn_cancel" value="确认编辑">
    </div>
</form>

<form class="layui-form " lay-filter="form_allocate" id="form_allocate" style="display:none;height: 100%;">
    
    <div style="height: 100%;">
        <div class="layui-form-item layui-hide">
            <input type="text" name="userid" lay-verify="required" placeholder="" autocomplete="off" class="layui-input" disabled>
        </div>
        <div class=" " >
            <ul id="treeDemo" class="ztree"></ul>
        </div>
        <div class="layui-form-item layui-hide">
            <input type="button" lay-submit lay-filter="btn_allocate" id="btn_allocate" value="确认添加">
            <input type="button" lay-submit lay-filter="btn_cancel" id="btn_cancel" value="确认编辑">
        </div>
    </div>
    
</form>
</html>

